package cn.worken.baseframe.common.util;

import cn.worken.baseframe.bean.enums.BaseEnum;

import java.util.Objects;
import java.util.stream.Stream;

/**
 * @author genxin.liu
 * @since 2021/12/27 17:41
 */
public class EnumUtil {
    
    /**
     * 根据code获取枚举
     *
     * @author genxin.liu
     * @date 2021/12/27 17:48
     * @param: code
     * @param: clazz
     * @return T
     */
    public static <T extends BaseEnum> T byCode(String code, Class<T> clazz) {
        checkEnumClass(clazz);
        T[] codes = clazz.getEnumConstants();
        return Stream.of(codes).filter(e -> Objects.equals(e.code(), code)).findFirst().orElseGet(null);
    }
    
    /**
     * 根据desc获取枚举
     *
     * @author genxin.liu
     * @date 2021/12/27 17:49
     * @param: desc
     * @param: clazz
     * @return T
     */
    public static <T extends BaseEnum> T byDesc(String desc, Class<T> clazz) {
        checkEnumClass(clazz);
        T[] codes = clazz.getEnumConstants();
        return Stream.of(codes).filter(e -> Objects.equals(e.desc(), desc)).findFirst().orElseGet(null);
    }
    
    /**
     * code转name
     *
     * @author genxin.liu
     * @date 2021/12/27 17:51
     * @param: code
     * @param: clazz
     * @return java.lang.String
     */
    public static String codeToDesc(String code, Class<? extends BaseEnum> clazz) {
        BaseEnum baseEnum = byCode(code, clazz);
        return Objects.nonNull(baseEnum) ? baseEnum.desc() : "";
    }
    
    /**
     * name转code
     *
     * @author genxin.liu
     * @date 2021/12/27 17:51
     * @param: desc
     * @param: clazz
     * @return java.lang.String
     */
    public static String descTCode(String desc, Class<? extends BaseEnum> clazz) {
        BaseEnum baseEnum = byDesc(desc, clazz);
        return Objects.nonNull(baseEnum) ? baseEnum.code() : "";
    }
    
    private static void checkEnumClass(Class clazz) {
        if (!clazz.isEnum()) {
            throw new IllegalArgumentException(clazz + " is not a enum");
        }
    }
    
}
